package com.wlr.study.leetcode.codethink;

/**
 * 螺旋矩阵
 */
public class SpiralMatrix {
    /*
     * 1 2 3
     * 8 9 4
     * 7 6 5
     *
     *  1  2  3  4
     * 12 13 14  5
     * 11 16 15  6
     * 10  9  8  7
     */
    public int[][] generateMatrix(int a) {
        int[][] result = new int[a][a];
        int startx = 0, starty = 0;
        int loop = a / 2;
        int mid = a / 2;
        int count = 1;
        int offset = 1;
        int i, j;
        while (loop > 0) {
            i = startx;
            j = starty;
            // 上侧从左到右
            for (; j < starty + a - offset; ++j) {
                result[startx][j] = count++;
            }
            // 右侧从上到下
            for (; i < startx + a - offset; ++i) {
                result[i][j] = count++;
            }
            // 下侧从右到左
            for (; j > starty; j--) {
                result[i][j] = count++;
            }
            // 左侧从下到上
            for (; i > startx; i--) {
                result[i][j] = count++;
            }

            loop--;

            startx += 1;
            starty += 1;

            offset += 2;
        }
        if (a % 2 == 1) {
            result[mid][mid] = count;
        }
        return result;
    }

    public static void main(String[] args) {
        SpiralMatrix spiralMatrix = new SpiralMatrix();
        int[][] ints = spiralMatrix.generateMatrix(3);
        for (int i = 0; i < ints.length; i++) {
            for (int j = 0; j < ints.length; j++) {
                System.out.println(ints[i][j]);
            }
        }
    }
}
